{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.metrics import mean_squared_error\n",
    "from lightgbm import LGBMRegressor\n",
    "from sklearnex import patch_sklearn\n",
    "# 设置支持中文的字体\n",
    "plt.rcParams['font.sans-serif'] = ['SimHei']  # 指定默认字体为黑体\n",
    "# 解决负号显示为方块的问题\n",
    "plt.rcParams['axes.unicode_minus'] = False"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 加载文件"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "all_data = pd.read_csv('./filtered_data/months1-9.csv', encoding='utf-8')\n",
    "export_file_path = './processed_data/non_proc_1-9.csv'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Columns with missing values:\n",
      "驱动电机控制器温度      123387\n",
      "驱动电机转速         123387\n",
      "驱动电机转矩         123387\n",
      "驱动电机温度         123387\n",
      "电机控制器输入电压      123387\n",
      "电机控制器直流母线电流    123387\n",
      "dtype: int64\n",
      "\n",
      "Missing values percentage:\n",
      "驱动电机控制器温度      10.58\n",
      "驱动电机转速         10.58\n",
      "驱动电机转矩         10.58\n",
      "驱动电机温度         10.58\n",
      "电机控制器输入电压      10.58\n",
      "电机控制器直流母线电流    10.58\n",
      "dtype: float64 %\n"
     ]
    }
   ],
   "source": [
    "missing_values = all_data.isnull().sum()\n",
    "columns_with_missing = missing_values[missing_values > 0]\n",
    "\n",
    "if len(columns_with_missing) > 0:\n",
    "    print(\"Columns with missing values:\")\n",
    "    print(columns_with_missing)\n",
    "    missing_percentage = (columns_with_missing / len(all_data)) * 100\n",
    "    print(\"\\nMissing values percentage:\")\n",
    "    print(missing_percentage.round(2), \"%\")\n",
    "else:\n",
    "    print(\"No missing values found in the dataset.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 预处理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "def preprocess(data: pd.DataFrame) -> pd.DataFrame:\n",
    "    # 删除缺失值\n",
    "    print(\"删除前：\", data.shape)\n",
    "    data = data.dropna()\n",
    "    print(\"删除后：\", data.shape)\n",
    "    # 删除时间列\n",
    "    data = data.drop('数据采集时间', axis=1)\n",
    "    # 所有的object数据类型转换为int类型\n",
    "    for col in data.columns:\n",
    "        if data[col].dtype == 'object':\n",
    "            data[col] = data[col].astype(int)\n",
    "    return data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 使用LightGBM进行补充缺失值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "删除前： (1166206, 21)\n",
      "删除后： (1042819, 21)\n"
     ]
    }
   ],
   "source": [
    "data = all_data.copy()\n",
    "data = preprocess(all_data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "to_processed_columns = ['驱动电机控制器温度', '驱动电机温度',\n",
    "                        '电机控制器输入电压', '电机控制器直流母线电流',\n",
    "                        '驱动电机转速', '驱动电机转矩'\n",
    "                        ]\n",
    "best_models = {}\n",
    "best_mses = {}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Processing column: 驱动电机控制器温度\n",
      "X shape: (1042819, 19)\n",
      "y shape: (1042819,)\n",
      "[LightGBM] [Info] Auto-choosing col-wise multi-threading, the overhead of testing was 0.057652 seconds.\n",
      "You can set `force_col_wise=true` to remove the overhead.\n",
      "[LightGBM] [Info] Total Bins 2937\n",
      "[LightGBM] [Info] Number of data points in the train set: 834255, number of used features: 19\n",
      "[LightGBM] [Info] Start training from score 37.089643\n",
      "Mean Squared Error: 2.4913136692933735\n",
      "Standardized Mean Squared Error: 0.023800691967729045\n",
      "Best Mean Squared Error: 2.4913136692933735\n",
      "Best Standardized MSE: 0.023800691967729045\n",
      "Best Model: LGBMRegressor(learning_rate=0.05, metric='rmse', n_estimators=1000,\n",
      "              num_leaves=2047, objective='regression', random_state=42)\n",
      "Processing column: 驱动电机温度\n",
      "X shape: (1042819, 19)\n",
      "y shape: (1042819,)\n",
      "[LightGBM] [Info] Auto-choosing col-wise multi-threading, the overhead of testing was 0.051815 seconds.\n",
      "You can set `force_col_wise=true` to remove the overhead.\n",
      "[LightGBM] [Info] Total Bins 2958\n",
      "[LightGBM] [Info] Number of data points in the train set: 834255, number of used features: 19\n",
      "[LightGBM] [Info] Start training from score 43.182655\n",
      "Mean Squared Error: 2.369992986516238\n",
      "Standardized Mean Squared Error: 0.02438057184730885\n",
      "Best Mean Squared Error: 2.369992986516238\n",
      "Best Standardized MSE: 0.02438057184730885\n",
      "Best Model: LGBMRegressor(learning_rate=0.05, metric='rmse', n_estimators=1000,\n",
      "              num_leaves=2047, objective='regression', random_state=42)\n",
      "Processing column: 电机控制器输入电压\n",
      "X shape: (1042819, 19)\n",
      "y shape: (1042819,)\n",
      "[LightGBM] [Info] Auto-choosing row-wise multi-threading, the overhead of testing was 0.008873 seconds.\n",
      "You can set `force_row_wise=true` to remove the overhead.\n",
      "And if memory is not enough, you can set `force_col_wise=true`.\n",
      "[LightGBM] [Info] Total Bins 2895\n",
      "[LightGBM] [Info] Number of data points in the train set: 834255, number of used features: 19\n",
      "[LightGBM] [Info] Start training from score 359.570123\n",
      "Mean Squared Error: 25.4265473115504\n",
      "Standardized Mean Squared Error: 0.0076451588554471055\n",
      "Best Mean Squared Error: 25.4265473115504\n",
      "Best Standardized MSE: 0.0076451588554471055\n",
      "Best Model: LGBMRegressor(learning_rate=0.05, metric='rmse', n_estimators=1000,\n",
      "              num_leaves=2047, objective='regression', random_state=42)\n",
      "Processing column: 电机控制器直流母线电流\n",
      "X shape: (1042819, 19)\n",
      "y shape: (1042819,)\n",
      "[LightGBM] [Info] Auto-choosing col-wise multi-threading, the overhead of testing was 0.015192 seconds.\n",
      "You can set `force_col_wise=true` to remove the overhead.\n",
      "[LightGBM] [Info] Total Bins 2774\n",
      "[LightGBM] [Info] Number of data points in the train set: 834255, number of used features: 19\n",
      "[LightGBM] [Info] Start training from score 8.163059\n",
      "Mean Squared Error: 0.31481128954932186\n",
      "Standardized Mean Squared Error: 0.0005458220973441054\n",
      "Best Mean Squared Error: 0.31481128954932186\n",
      "Best Standardized MSE: 0.0005458220973441054\n",
      "Best Model: LGBMRegressor(learning_rate=0.05, metric='rmse', n_estimators=1000,\n",
      "              num_leaves=2047, objective='regression', random_state=42)\n",
      "Processing column: 驱动电机转速\n",
      "X shape: (1042819, 19)\n",
      "y shape: (1042819,)\n",
      "[LightGBM] [Info] Auto-choosing row-wise multi-threading, the overhead of testing was 0.009596 seconds.\n",
      "You can set `force_row_wise=true` to remove the overhead.\n",
      "And if memory is not enough, you can set `force_col_wise=true`.\n",
      "[LightGBM] [Info] Total Bins 2774\n",
      "[LightGBM] [Info] Number of data points in the train set: 834255, number of used features: 19\n",
      "[LightGBM] [Info] Start training from score 1345.943486\n",
      "Mean Squared Error: 275.86304191560833\n",
      "Standardized Mean Squared Error: 0.00017764985406576594\n",
      "Best Mean Squared Error: 275.86304191560833\n",
      "Best Standardized MSE: 0.00017764985406576594\n",
      "Best Model: LGBMRegressor(learning_rate=0.05, metric='rmse', n_estimators=1000,\n",
      "              num_leaves=2047, objective='regression', random_state=42)\n",
      "Processing column: 驱动电机转矩\n",
      "X shape: (1042819, 19)\n",
      "y shape: (1042819,)\n",
      "[LightGBM] [Info] Auto-choosing row-wise multi-threading, the overhead of testing was 0.007478 seconds.\n",
      "You can set `force_row_wise=true` to remove the overhead.\n",
      "And if memory is not enough, you can set `force_col_wise=true`.\n",
      "[LightGBM] [Info] Total Bins 2774\n",
      "[LightGBM] [Info] Number of data points in the train set: 834255, number of used features: 19\n",
      "[LightGBM] [Info] Start training from score 11.805694\n",
      "Mean Squared Error: 21.5560909736594\n",
      "Standardized Mean Squared Error: 0.009221693405118735\n",
      "Best Mean Squared Error: 21.5560909736594\n",
      "Best Standardized MSE: 0.009221693405118735\n",
      "Best Model: LGBMRegressor(learning_rate=0.05, metric='rmse', n_estimators=1000,\n",
      "              num_leaves=2047, objective='regression', random_state=42)\n"
     ]
    }
   ],
   "source": [
    "for column_name in to_processed_columns:\n",
    "    print(f\"Processing column: {column_name}\")\n",
    "    data[column_name] = data[column_name].astype('int16')\n",
    "    X = data.drop(column_name, axis=1)\n",
    "    y = data[column_name]\n",
    "    print(\"X shape:\", X.shape)\n",
    "    print(\"y shape:\", y.shape)\n",
    "\n",
    "    # 划分数据集\n",
    "    X_train, X_valid, y_train, y_valid = train_test_split(\n",
    "        X, y, test_size=0.2, random_state=42)\n",
    "\n",
    "    best_mse = np.inf\n",
    "    best_model = None\n",
    "\n",
    "    # for nl in [1023,2047,4095]: 2047 目前是最好的\n",
    "    for nl in [2047]:\n",
    "        model = LGBMRegressor(\n",
    "            objective='regression', metric='rmse',\n",
    "            boosting_type='gbdt', random_state=42,\n",
    "            learning_rate=0.05, num_leaves=nl, n_estimators=1000)\n",
    "\n",
    "        model.fit(X_train, y_train)\n",
    "        y_pred = model.predict(X_valid)\n",
    "\n",
    "        # 计算标准MSE\n",
    "        mse = mean_squared_error(y_valid, y_pred)\n",
    "\n",
    "        # 计算标准化MSE（除以目标变量的方差）\n",
    "        standardized_mse = mse / np.var(y_valid)\n",
    "\n",
    "        print(f\"Mean Squared Error: {mse}\")\n",
    "        print(f\"Standardized Mean Squared Error: {standardized_mse}\")\n",
    "\n",
    "        if mse < best_mse:\n",
    "            best_mse = mse\n",
    "            best_model = model\n",
    "\n",
    "    print(f\"Best Mean Squared Error: {best_mse}\")\n",
    "    print(f\"Best Standardized MSE: {best_mse / np.var(y_valid)}\")\n",
    "    print(f\"Best Model: {best_model}\")\n",
    "\n",
    "    if best_mse < best_mses.get(column_name, np.inf):\n",
    "        best_models[column_name] = best_model\n",
    "        best_mses[column_name] = best_mse"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 保存模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model for 驱动电机控制器温度 saved to model/驱动电机控制器温度_best_lgb_model.pkl\n",
      "Model for 驱动电机温度 saved to model/驱动电机温度_best_lgb_model.pkl\n",
      "Model for 电机控制器输入电压 saved to model/电机控制器输入电压_best_lgb_model.pkl\n",
      "Model for 电机控制器直流母线电流 saved to model/电机控制器直流母线电流_best_lgb_model.pkl\n",
      "Model for 驱动电机转速 saved to model/驱动电机转速_best_lgb_model.pkl\n",
      "Model for 驱动电机转矩 saved to model/驱动电机转矩_best_lgb_model.pkl\n"
     ]
    }
   ],
   "source": [
    "import joblib\n",
    "import os\n",
    "os.makedirs('model', exist_ok=True)\n",
    "# 保存每个最优模型\n",
    "for column, model in best_models.items():\n",
    "    model_path = f'model/{column}_best_lgb_model.pkl'\n",
    "    joblib.dump(model, model_path)\n",
    "    print(f\"Model for {column} saved to {model_path}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 使用多变量插补"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.experimental import enable_iterative_imputer\n",
    "from sklearn.impute import IterativeImputer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "删除前： (1166206, 21)\n",
      "删除后： (1166206, 21)\n"
     ]
    }
   ],
   "source": [
    "data = all_data.__deepcopy__()\n",
    "data = preprocess(all_data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "to_processed_columns = [\n",
    "    '驱动电机控制器温度', '驱动电机温度',\n",
    "    '电机控制器输入电压', '电机控制器直流母线电流',\n",
    "    '驱动电机转速', '驱动电机转矩'\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Processing column: 驱动电机控制器温度\n",
      "原始数据中驱动电机控制器温度的NaN值数量: 0\n",
      "填补后数据中驱动电机控制器温度的NaN值数量: 0\n",
      "驱动电机控制器温度 - 填补后的均方误差: 3.7264727855680624\n",
      "驱动电机控制器温度 - 填补后的标准化均方误差: 0.03151716901830042\n",
      "Processing column: 驱动电机温度\n",
      "原始数据中驱动电机温度的NaN值数量: 0\n",
      "填补后数据中驱动电机温度的NaN值数量: 0\n",
      "驱动电机温度 - 填补后的均方误差: 3.0811477982799103\n",
      "驱动电机温度 - 填补后的标准化均方误差: 0.02597986347856329\n",
      "Processing column: 电机控制器输入电压\n",
      "原始数据中电机控制器输入电压的NaN值数量: 0\n",
      "填补后数据中电机控制器输入电压的NaN值数量: 0\n",
      "电机控制器输入电压 - 填补后的均方误差: 15.269327802651611\n",
      "电机控制器输入电压 - 填补后的标准化均方误差: 0.005011137184466299\n",
      "Processing column: 电机控制器直流母线电流\n",
      "原始数据中电机控制器直流母线电流的NaN值数量: 0\n",
      "填补后数据中电机控制器直流母线电流的NaN值数量: 0\n",
      "电机控制器直流母线电流 - 填补后的均方误差: 14.486709457960858\n",
      "电机控制器直流母线电流 - 填补后的标准化均方误差: 0.02687493421158081\n",
      "Processing column: 驱动电机转速\n",
      "原始数据中驱动电机转速的NaN值数量: 0\n",
      "填补后数据中驱动电机转速的NaN值数量: 0\n",
      "驱动电机转速 - 填补后的均方误差: 1581.778409279755\n",
      "驱动电机转速 - 填补后的标准化均方误差: 0.001019021173892042\n",
      "Processing column: 驱动电机转矩\n",
      "原始数据中驱动电机转矩的NaN值数量: 0\n",
      "填补后数据中驱动电机转矩的NaN值数量: 0\n",
      "驱动电机转矩 - 填补后的均方误差: 113.39005857701152\n",
      "驱动电机转矩 - 填补后的标准化均方误差: 0.05307976140616395\n"
     ]
    }
   ],
   "source": [
    "for column_name in to_processed_columns:\n",
    "    print(f\"Processing column: {column_name}\")\n",
    "\n",
    "    # 模拟缺失值\n",
    "    data = data.dropna(subset=[column_name])\n",
    "    origin_data = data.copy()  # 创建原始数据的副本\n",
    "    null_data = data.copy()\n",
    "    # 使用数据的20%来模拟缺失值\n",
    "    null_data.loc[null_data.sample(frac=0.2).index, column_name] = np.nan\n",
    "    # 使用多重插补填补缺失值\n",
    "    imputer = IterativeImputer(max_iter=10, random_state=42)\n",
    "    data_filled = imputer.fit_transform(null_data)\n",
    "    data_filled = pd.DataFrame(data_filled, columns=data.columns)\n",
    "    print(\n",
    "        f\"原始数据中{column_name}的NaN值数量: {origin_data[column_name].isna().sum()}\")\n",
    "    print(\n",
    "        f\"填补后数据中{column_name}的NaN值数量: {data_filled[column_name].isna().sum()}\")\n",
    "\n",
    "    # 计算这些位置上填补值与原始值的MSE\n",
    "    mse = mean_squared_error(\n",
    "        origin_data[column_name],\n",
    "        data_filled[column_name]\n",
    "    )\n",
    "    # 计算标准化MSE（除以目标变量的方差）\n",
    "    standardized_mse = mse / np.var(origin_data[column_name])\n",
    "\n",
    "    print(f\"{column_name} - 填补后的均方误差: {mse}\")\n",
    "    print(f\"{column_name} - 填补后的标准化均方误差: {standardized_mse}\")\n",
    "\n",
    "    best_mses[column_name] = mse\n",
    "    best_models[column_name] = imputer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model for 驱动电机控制器温度 saved to model/驱动电机控制器温度_best_model.pkl\n",
      "Model for 驱动电机温度 saved to model/驱动电机温度_best_model.pkl\n",
      "Model for 电机控制器输入电压 saved to model/电机控制器输入电压_best_model.pkl\n",
      "Model for 电机控制器直流母线电流 saved to model/电机控制器直流母线电流_best_model.pkl\n",
      "Model for 驱动电机转速 saved to model/驱动电机转速_best_model.pkl\n",
      "Model for 驱动电机转矩 saved to model/驱动电机转矩_best_model.pkl\n"
     ]
    }
   ],
   "source": [
    "for column, model in best_models.items():\n",
    "    model_path = f'model/{column}_best_model.pkl'\n",
    "    joblib.dump(model, model_path)\n",
    "    print(f\"Model for {column} saved to {model_path}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "以驱动电机控制器温度为例 \\\n",
    "在保证数据都是以80%,20%的比例进行划分的情况下，LightGBM的时间消耗最少，误差相对合理，所以选择LightGBM进行处理 \\\n",
    "而驱动电机转速和驱动电机转矩在三个模型均方误差的对比下，多变量插补更优，所以选择多变量插补进行处理"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 预测"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "preds_data = {}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### LightGBM"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 加载模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "import joblib"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model for 驱动电机控制器温度 loaded successfully from model/驱动电机控制器温度_best_lgb_model.pkl\n",
      "Model for 驱动电机温度 loaded successfully from model/驱动电机温度_best_lgb_model.pkl\n",
      "Model for 电机控制器输入电压 loaded successfully from model/电机控制器输入电压_best_lgb_model.pkl\n",
      "Model for 电机控制器直流母线电流 loaded successfully from model/电机控制器直流母线电流_best_lgb_model.pkl\n",
      "Model for 驱动电机转速 loaded successfully from model/驱动电机转速_best_lgb_model.pkl\n",
      "Model for 驱动电机转矩 loaded successfully from model/驱动电机转矩_best_lgb_model.pkl\n",
      "Loaded 6 LightGBM models\n"
     ]
    }
   ],
   "source": [
    "# 加载保存好的LightGBM模型\n",
    "best_models = {}\n",
    "for column_name in to_processed_columns:\n",
    "    model_path = f'model/{column_name}_best_model.pkl'\n",
    "    try:\n",
    "        best_models[column_name] = joblib.load(model_path)\n",
    "        print(f\"Model for {column_name} loaded successfully from {model_path}\")\n",
    "    except FileNotFoundError:\n",
    "        print(f\"Model file not found for {column_name} at {model_path}\")\n",
    "    except Exception as e:\n",
    "        print(f\"Error loading model for {column_name}: {str(e)}\")\n",
    "\n",
    "print(f\"Loaded {len(best_models)} LightGBM models\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "由于温度本质上还是连续型变量，所以这里采用回归的方法训练模型，最后将小数位数取整，得到最终的结果。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "preds_columns = [\n",
    "    '驱动电机控制器温度',\n",
    "    '驱动电机温度',\n",
    "    '电机控制器输入电压',\n",
    "    '电机控制器直流母线电流',\n",
    "    '驱动电机转速',\n",
    "    '驱动电机转矩'\n",
    "]\n",
    "preds_data = {}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Processing column: 驱动电机控制器温度\n",
      "(123387, 21)\n",
      "Other columns: ['驱动电机温度', '电机控制器输入电压', '电机控制器直流母线电流', '驱动电机转速', '驱动电机转矩']\n",
      "Processing column: 驱动电机温度\n",
      "(123387, 21)\n",
      "Other columns: ['驱动电机控制器温度', '电机控制器输入电压', '电机控制器直流母线电流', '驱动电机转速', '驱动电机转矩']\n",
      "Processing column: 电机控制器输入电压\n",
      "(123387, 21)\n",
      "Other columns: ['驱动电机控制器温度', '驱动电机温度', '电机控制器直流母线电流', '驱动电机转速', '驱动电机转矩']\n",
      "Processing column: 电机控制器直流母线电流\n",
      "(123387, 21)\n",
      "Other columns: ['驱动电机控制器温度', '驱动电机温度', '电机控制器输入电压', '驱动电机转速', '驱动电机转矩']\n",
      "Processing column: 驱动电机转速\n",
      "(123387, 21)\n",
      "Other columns: ['驱动电机控制器温度', '驱动电机温度', '电机控制器输入电压', '电机控制器直流母线电流', '驱动电机转矩']\n",
      "Processing column: 驱动电机转矩\n",
      "(123387, 21)\n",
      "Other columns: ['驱动电机控制器温度', '驱动电机温度', '电机控制器输入电压', '电机控制器直流母线电流', '驱动电机转速']\n"
     ]
    }
   ],
   "source": [
    "for column_name in preds_columns:\n",
    "    print(f\"Processing column: {column_name}\")\n",
    "\n",
    "    # 复制数据\n",
    "    data = all_data.__deepcopy__()\n",
    "\n",
    "    # 只保留要预测列的空值\n",
    "    data_to_predict = data[pd.isna(data[column_name])]\n",
    "\n",
    "    print(data_to_predict.shape)\n",
    "\n",
    "    # 删除其他预测列的空值\n",
    "    other_columns = [col for col in preds_columns if col != column_name]\n",
    "    print(f\"Other columns: {other_columns}\")\n",
    "    data = data.dropna(subset=other_columns)\n",
    "\n",
    "    if not data_to_predict.empty:\n",
    "        # 删除时间列\n",
    "        data_to_predict = data_to_predict.drop('数据采集时间', axis=1)\n",
    "\n",
    "        # 所有的object数据类型转换为int类型\n",
    "        for col in data_to_predict.columns:\n",
    "            if data_to_predict[col].dtype == 'object':\n",
    "                data_to_predict[col] = data_to_predict[col].astype(int)\n",
    "\n",
    "        # 预测\n",
    "        preds_data[column_name] = best_models[column_name].predict(\n",
    "            data_to_predict.drop(columns=[column_name]))\n",
    "\n",
    "        # 将预测值填充回原数据\n",
    "        all_data.loc[data_to_predict.index,\n",
    "                     column_name] = preds_data[column_name]\n",
    "    else:\n",
    "        print(f\"No missing values found for column: {column_name}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 保存数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "all_data.to_csv(export_file_path,\n",
    "                index=False, encoding='utf-8')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "DataAnalysis",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.15"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
